package com.xdkj.es.service;

import com.xdkj.es.dao.JDGoodsDao;
import com.xdkj.es.entiti.JDGoods;
import com.xdkj.es.util.HtmlParseUtil;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author joke
 * @version 1.0
 * @date 2021/12/19-18:53
 */
@Service
public class JDGoodsService {
    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Autowired
    JDGoodsDao jdGoodsDao;

    /**
     * 初始化数据
     * 解析数据放入到中
     */
    public Boolean initData(String keyword) throws Exception {
        //根据关键词查询数据
        List<JDGoods> jdGoods = new HtmlParseUtil().JDSearch(keyword);
        System.out.println("----------------------------------");
        System.out.println(jdGoods);
        //批量插入数据
        Iterable<JDGoods> save = jdGoodsDao.saveAll(jdGoods);

        return save != null ? true : false;
    }

    /**
     * 高亮查询数据
     */
    public List<Map<String, Object>> searchPage(String keyword, Integer page, Integer limit) {
        if (page == null || page < 1) {
            page = 1;
        }
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder
                .field("title")
                .preTags("<span style='color:red;'>")
                .postTags("</span>");

        NativeSearchQuery searchQueryBuilder = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.multiMatchQuery(keyword, "title"))
                .withPageable(PageRequest.of(0, 10))
                .withHighlightBuilder(highlightBuilder).build();

        SearchHits<JDGoods> search = elasticsearchRestTemplate.search(searchQueryBuilder, JDGoods.class);
        //System.out.println(search);
        List<Map<String, Object>> list = new ArrayList<>();
        List<Map<String, Object>> collect = search.getSearchHits().stream().map(hit -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", hit.getId());
            map.put("title", hit.getContent().getTitle());
            map.put("img", hit.getContent().getImg());
            map.put("price", hit.getContent().getPrice());
            map.put("publish", hit.getContent().getPublish());
            map.put("heightTitle", hit.getHighlightField("title"));
            return map;
        }).collect(Collectors.toList());
        return collect;
    }
}
